/*
 * ParallelWorker.h
 *
 *  Created on: Jan 9, 2013
 *      Author: fs
 */

#ifndef PARALLELWORKER_H_
#define PARALLELWORKER_H_

#include <vector>
#include "DataTypes.h"
#include "GenCalc.h"
#include "tbb/blocked_range.h"

class ParallelWorker
{
	std::vector<member> population;
	GenCalc* calc;
	data* datas;


public:
	ParallelWorker(
			std::vector<member> population,
			GenCalc* calc,
			data* datas):	population(population), calc(calc), datas(datas) {};

	void operator()(const tbb::blocked_range<int>& r) const
	{
		for(int i=r.begin(); i<r.end(); i++)
		{
			double fit = fitness(population.at(i));
			calc->writeFittnesAtPosition(fit, i);
		}
	}

	virtual ~ParallelWorker();

private:

	double fitness(member inputMember) const
	{
			double res = 0;
			double* gens = inputMember.gens;

			double p = gens[0];
			double cg =gens[1];
			double c = gens[2];
			double dt =gens[3];
			double k = gens[4];

			for (int i = 0; i < datas->length; i++)
			{
				double ecg = datas->items[i].ecg;
				if (calc->checkTimeCondition(k, dt, ecg))
				{
					res = WORSE_FITTNES;
					return res;
				}

				double left_side = p * datas->items[i].bg+ cg * datas->items[i].bg * ecg + c;
				double index_time = datas->items[i].time + dt + k * dt * ecg;
				double ig;

				if (calc->getIg(index_time * (24 * 60 * 60), &ig) == 1)
				{
					double right_side = ig;
					res += fabs(right_side - left_side);
				}
			}

		return res;
	}
};

#endif /* PARALLELWORKER_H_ */
